import Https from "@/utils/Https";
import { ProTable } from "@ant-design/pro-components";
import {
  Button,
  Card,
  DatePicker,
  Descriptions,
  message,
  Space,
  Tag,
  Spin,
  Popconfirm,
} from "antd";
import dayjs from "dayjs";
import { FC, useEffect, useRef, useState } from "react";
import { calcColumns, BtnList } from "../configFile";
import OrderModal from "../orderModal";
import styles from "../index.less";
import { history } from "umi";
const { RangePicker } = DatePicker;
const Order: FC<any> = () => {
  const actionRef = useRef();
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [pageInfo, setPageInfo] = useState<any>({});
  const [title, setTitle] = useState("");
  const [type, setType] = useState("2");
  const [search, setSearch] = useState({
    startTime: "",
    endTime: "",
  });
  //获取当前套餐信息
  const getPackageInfo = async () => {
    setLoading(true);
    let res = await Https.get("/band/package/getPackageInfo", {}, true);
    setLoading(false);
    if (res.code == 200) {
      setPageInfo(res.data);
    } else {
      setPageInfo({});
      message.error(res.msg);
    }
  };
  //获取购买记录
  const getList = async (params) => {
    let records = [];
    let total = 0;
    setLoading(true);
    let obj = {
      ...params,
      ...search,
    };
    let res: any = await Https.get("/band/package/buyRecordList", obj, true);
    if (res.code == 200) {
      records = res.data.records;
      total = res.data.total;
    } else {
      message.error(res.msg);
    }
    setLoading(false);
    return { success: true, data: records, total };
  };
  //取消订单
  const deleteItem = async (id) => {
    let res = await Https.post(`/band/package/cancel/${id}`, {}, true);
    if (res.code == 200) {
      message.success("操作成功");
      actionRef.current && actionRef.current.reload();
    } else {
      message.error(res.msg);
    }
  };

  //获取订单状态
  const getOrderStatus = async (id) => {
    let res = await Https.get(`/package/salerecord/queryOrder`, { id }, true);
    if (res.code == 200) {
      if (res.data) {
        actionRef.current && actionRef.current.reload();
      } else {
        message.info(res.msg);
      }
    } else {
      message.error(res.msg);
    }
  };
  const operate = {
    title: "操作",
    dataIndex: "operate",
    align: "left",
    fixed: "right",
    width: 250,
    render: (_, row) => {
      return row.orderStatus == "0" ? (
        <Space>
          <a
            onClick={() => {
              history.push(`/brand/order/${row.id}/2`);
            }}
          >
            支付
          </a>
          <a
            onClick={() => {
              getOrderStatus(row.id);
            }}
          >
            更新订单状态
          </a>
          <Popconfirm
            title="确定要取消订单吗?"
            onConfirm={() => {
              deleteItem(row.id);
            }}
          >
            <a type="link" style={{ color: "red" }}>
              取消订单
            </a>
          </Popconfirm>
        </Space>
      ) : (
        <a
          onClick={() => {
            history.push(`/brand/order/${row.id}/2`);
          }}
        >
          详情
        </a>
      );
    },
  };
  useEffect(() => {
    getPackageInfo();
  }, []);
  return (
    <Spin spinning={loading}>
      <Card
        title="当前套餐"
        className={styles.OrderInfo}
        extra={
          <Space>
            {pageInfo.buttonVoList &&
              pageInfo.buttonVoList.length > 0 &&
              pageInfo.buttonVoList.map((item) => (
                <Button
                  onClick={() => {
                    setOpen(true);
                    setTitle(
                      item.buttonType == "3"
                        ? "加购场馆"
                        : BtnList[item.buttonType]
                    );
                    setType(item.buttonType);
                  }}
                  type={
                    item.buttonType == "2"
                      ? "primary"
                      : item.buttonType == "3"
                      ? "link"
                      : "default"
                  }
                  key={item.buttonType}
                  disabled={item.disable == "2"}
                >
                  {BtnList[item.buttonType]}
                </Button>
              ))}
          </Space>
        }
      >
        <Descriptions layout="vertical" title="">
          <Descriptions.Item label="套餐名称">
            {pageInfo.packageName}
          </Descriptions.Item>
          <Descriptions.Item label="可创建场馆数量">
            {pageInfo.venueNum}
          </Descriptions.Item>
          <Descriptions.Item label="有效期至">
            {pageInfo.isForever == "1"
              ? "永久"
              : pageInfo.validityDate
              ? dayjs(pageInfo.validityDate).format("YYYY-MM-DD")
              : "-"}
            <Tag
              style={{ marginLeft: "10px" }}
              color={pageInfo.status == "1" ? "green" : "default"}
            >
              {pageInfo.status == "1" ? "生效中" : "已失效"}
            </Tag>
          </Descriptions.Item>
        </Descriptions>
      </Card>
      <Card
        title="购买记录"
        extra={
          <RangePicker
            onChange={(e) => {
              let startTime;
              let endTime;
              if (e && e.length > 0) {
                startTime = dayjs(e[0]).format("YYYY-MM-DD");
                endTime = dayjs(e[1]).format("YYYY-MM-DD");
              } else {
                startTime = "";
                endTime = "";
              }
              setSearch({ startTime, endTime });
              actionRef.current && actionRef.current.reload();
            }}
          />
        }
        style={{ marginTop: "20px" }}
      >
        <ProTable
          search={false}
          rowKey="id"
          actionRef={actionRef}
          toolBarRender={false}
          request={async (params, sorter, filter) => {
            let obj = {
              ...params,
            };
            if (sorter) {
              obj.orderByColumn = Object.keys(sorter)[0];
              obj.isAsc = Object.values(sorter)[0];
            }
            return await getList(obj);
          }}
          loading={loading}
          scroll={{ x: 1500 }}
          pagination={{
            showSizeChanger: true,
          }}
          columns={calcColumns({ operate })}
        />
      </Card>
      <OrderModal
        open={open}
        title={title}
        type={type}
        onClose={() => {
          setOpen(false);
        }}
        activeKey={"2"}
      ></OrderModal>
    </Spin>
  );
};
export default Order;
